const app = getApp();
const api = require('../../../../ws_micro_shop/utils/api.js');
const { throttle, handleReplaceComma } = require('../../../common/utils/util');

Page({
  data: {
    showMask: false,
    weeks: [], //日期列表
    singleDistributionList: [], //单一分配列表
    uniformDistributionList: [], //统一分配列表
    singleDisabled: true, //单一分配按钮
    uniformDisabled: true, //统一分配按钮
    sales: 0,
    members: 0,
    isSelectAll: false,
    selectedNumber: 0,
    currentIndex: 0,
    week: '',
    totalPrice: 0,
    totalNum: 0,
    totalAllGoods: 0,
    totalShareDis: 0,
    totalShareMs: 0,
    totalShareCoupon: 0,
    totalMember: 0,
    uniformNewGoods: '',
    uniformHotGoods: '',
    uniformAllGoods: '',
    uniformShareDiscounts: '',
    uniformShareMs: '',
    uniformShareCoupons: '',
    uniformNewMember: '',
    toView: ''
  },

  onShow() {
    const { date = '', store_type = '' } = this.options;
    let corpid = wx.getStorageSync('corpid');
    let yearWeek = this.getYearWeek();
    this.setData(
      {
        ipX: wx.systemInfo && wx.systemInfo.model.search('iPhone X') !== -1,
        date,
        store_type,
        corpid,
        is_guide: app.ws_micro_shop_globalData.role,
        isSaas: app.ws_micro_shop_globalData.isSaas,
        yearWeek,
        week: yearWeek,
        currentIndex: yearWeek,
        toView: 'item' + yearWeek,
      },
      () => {
        this.getInfo();
      },
    );
  },

  getYearWeek() {
    var date1 = new Date(),
        date2 = new Date(date1.getFullYear(), 0, 1),
        d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000);
    return Math.ceil((d + ((date2.getDay() + 1) - 1)) / 7);
  },

  getInfo() {
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });

    const { date, week } = this.data;
    app.ws_micro_shoprequest({
      url: api.staff.submit_preview,
      data: {
        type: 2,
        date,
        week,
      },
      success: res => { 
        if (res && res.code === 0) {
          const { weeks = [], list: singleDistributionList = [] } = res.data;
          const uniformDistributionList = singleDistributionList[0] && singleDistributionList[0].list;
          uniformDistributionList.map(item => (item.checked = false));

          this.setData(
            {
              singleDistributionList,
              uniformDistributionList,
              weeks,
              week: week || (weeks[0] && weeks[0].value),
            },
            () => {
              this.checkButtonStatus();
              this.handleCalculateTotal();
            },
          );
        }
      },
      complete: res => {
        wx.hideLoading();
      },
    });
  },

  handleSingleSetting(e) {
    //单一设置
    const { singleDistributionList } = this.data;
    const { distributiontype = '', inputtype = '', id = '' } = e.currentTarget.dataset;

    singleDistributionList[0].list.map(item => {
      if (String(item.id) === String(id)) {
        item[inputtype] = e.detail.value;
      }
    });

    this.setData(
      {
        singleDistributionList,
      },
      () => {
        this.checkButtonStatus(distributiontype);
        this.handleCalculateTotal();
      },
    );
  },

  onSingleDistribution: throttle(function() {
    //单一分配 (这里的逻辑需要兼容之前的写法，待修改)
    const {
      is_guide = '',
      date = '',
      store_type = '',
      week,
      totalPrice,
      totalNum,
      totalAllGoods,
      totalShareDis,
      totalShareMs,
      totalShareCoupon,
      totalMember,
      uniformDistributionList,
      singleDistributionList,
    } = this.data;
    const arr = singleDistributionList[0].list;
    let promptText = '';
    let selectedArr = [];

    arr.map(item => {
      item.new_goods = handleReplaceComma(item.new_goods);
      item.hot_goods = handleReplaceComma(item.hot_goods);
      item.all_goods = handleReplaceComma(item.all_goods);
      item.share_discounts = handleReplaceComma(item.share_discounts);
      item.share_ms = handleReplaceComma(item.share_ms);
      item.share_coupons = handleReplaceComma(item.share_coupons);
      item.new_member = handleReplaceComma(item.new_member);
    })

    for (let index = 0; index < arr.length; index++) {
      if(
        String( arr[index].new_goods) === '0' ||
        String( arr[index].hot_goods) === '0' ||
        String( arr[index].all_goods) === '0' ||
        String( arr[index].share_discounts) === '0' ||
        String( arr[index].share_ms) === '0' ||
        String( arr[index].share_coupons) === '0' ||
        String( arr[index].new_member) === '0'
      ) {
        promptText = '目标设置需>0';
      }else{
        if( 
           arr[index].new_goods &&
           arr[index].hot_goods &&
           arr[index].all_goods &&
           arr[index].share_discounts &&
           arr[index].share_ms &&
           arr[index].share_coupons &&
           arr[index].new_member
        ) {
          selectedArr.push(arr[index]);
          continue;
        }
        if( 
          arr[index].new_goods ||
          arr[index].hot_goods ||
          arr[index].all_goods ||
          arr[index].share_discounts ||
          arr[index].share_ms ||
          arr[index].share_coupons ||
          arr[index].new_member
        ) {
          promptText = ' 被分配的导购需同时设置所有任务目标';
        }
      }
    }

    if(promptText) {
      wx.showModal({
        title: '系统提示',
        content: promptText,
        showCancel: false,
      });
      return;
    }

    app.infomation = {
      date,
      info: JSON.stringify(arr),
    };

    app.ws_micro_shoprequest({
      url: api.staff.task_submit,
      data: {
        date,
        info: JSON.stringify(singleDistributionList[0] && singleDistributionList[0].list),
        week,
      },
      method: 'post',
      success: function(res) {
        if (res && res.code === 0) {
          app.util.navigateTo(
            '/ws_micro_shop_guide/pages/achieve-succ/index',
            {
              store_type,
              date,
              sum: uniformDistributionList.length,
              num: selectedArr.length,
              totalPrice,
              totalNum,
              totalAllGoods,
              totalShareDis,
              totalShareMs,
              totalShareCoupon,
              totalMember,
            },
            false,
          );
        }
      },
    });
  },1000),

  handleUniformSetting(e) {
    //统一设置
    const { distributiontype = '', inputtype = '' } = e.currentTarget.dataset;

    this.setData(
      {
        [inputtype]: e.detail.value,
      },
      () => {
        this.checkButtonStatus(distributiontype);
      },
    );
  },

  onUniformDistribution: throttle(function() {
    //统一分配 (这里的逻辑需要兼容之前的写法，待修改)
    let {
      is_guide = '',
      date = '',
      store_type = '',
      week,
      uniformNewGoods,
      uniformHotGoods,
      uniformAllGoods,
      uniformShareDiscounts,
      uniformShareMs,
      uniformShareCoupons,
      uniformNewMember,
      uniformDistributionList,
      singleDistributionList,
      selectedNumber,
    } = this.data;
    const selectedList = [];
    let promptText = '';

    uniformNewGoods = handleReplaceComma(uniformNewGoods)
    uniformHotGoods =  handleReplaceComma(uniformHotGoods)
    uniformAllGoods =  handleReplaceComma(uniformAllGoods)
    uniformShareDiscounts =  handleReplaceComma(uniformShareDiscounts)
    uniformShareMs =  handleReplaceComma(uniformShareMs)
    uniformShareCoupons =  handleReplaceComma(uniformShareCoupons)
    uniformNewMember =  handleReplaceComma(uniformNewMember)

    uniformDistributionList
      .filter(item => item.checked)
      .map(uniformItem => {
        singleDistributionList[0] &&
          singleDistributionList[0].list.map(singleItem => {
            if (singleItem.id === uniformItem.id) {
              singleItem.new_goods = uniformNewGoods;
              singleItem.hot_goods = uniformHotGoods;
              singleItem.all_goods = uniformAllGoods;
              singleItem.share_discounts = uniformShareDiscounts;
              singleItem.share_ms = uniformShareMs;
              singleItem.share_coupons = uniformShareCoupons;
              singleItem.new_member = uniformNewMember;
              selectedList.push(singleItem);
            }
          });
      });

    selectedList.map(item => {
      if(
        String( item.new_goods) === '0' ||
        String( item.hot_goods) === '0' ||
        String( item.all_goods) === '0' ||
        String( item.share_discounts) === '0' ||
        String( item.share_ms) === '0' ||
        String( item.share_coupons) === '0' ||
        String( item.new_member) === '0'
      ) {
        promptText = '目标设置需>0';
      }
    });

    if(promptText) {
      wx.showModal({
        title: '系统提示',
        content: promptText,
        showCancel: false,
      });
      return;
    }

    app.infomation = {
      date,
      info: JSON.stringify(selectedList),
    };

    const totalPrice = uniformNewGoods * selectedNumber;
    const totalNum = uniformHotGoods * selectedNumber;
    const totalAllGoods = uniformAllGoods * selectedNumber;
    const totalShareDis = uniformShareDiscounts * selectedNumber;
    const totalShareMs = uniformShareMs * selectedNumber;
    const totalShareCoupon = uniformShareCoupons * selectedNumber;
    const totalMember = uniformNewMember * selectedNumber;
    app.ws_micro_shoprequest({
      url: api.staff.task_submit,
      data: {
        date,
        info: JSON.stringify(selectedList),
        week,
      },
      method: 'post',
      success: res => {
        if (res && res.code === 0) {
          app.util.navigateTo(
            '/ws_micro_shop_guide/pages/achieve-succ/index',
            {
              store_type,
              date,
              sum: uniformDistributionList.length,
              num: selectedNumber,
              totalPrice,
              totalNum,
              totalAllGoods,
              totalShareDis,
              totalShareMs,
              totalShareCoupon,
              totalMember,
            },
            false,
          );

          setTimeout(()=> {
            this.togglesMask();
          }, 1500);
        }
      },
    });
  },1000),

  handleCalculateTotal() {
    //计算单一设置下的合计
    const { singleDistributionList } = this.data;

    let totalPrice = 0;
    let totalNum = 0;
    let totalAllGoods = 0;
    let totalShareDis = 0;
    let totalShareMs = 0;
    let totalShareCoupon = 0;
    let totalMember = 0;

    singleDistributionList[0].list.map(item => {
      totalPrice += handleReplaceComma(item.new_goods,false);
      totalNum += handleReplaceComma(item.hot_goods,false);
      totalAllGoods += handleReplaceComma(item.all_goods,false);
      totalShareDis += handleReplaceComma(item.share_discounts,false);
      totalShareMs += handleReplaceComma(item.share_ms,false);
      totalShareCoupon += handleReplaceComma(item.share_coupons,false);
      totalMember += handleReplaceComma(item.new_member,false);
    });

    this.setData({
      totalPrice,
      totalNum,
      totalAllGoods,
      totalShareDis,
      totalShareMs,
      totalShareCoupon,
      totalMember,
    });
  },

  checkButtonStatus(distributiontype = 'single') {
    if (distributiontype === 'single') {
      const { singleDistributionList } = this.data;
      const notSelectedArr = [];
      singleDistributionList[0].list.map(item => {
        if (
          item.new_goods &&
          item.hot_goods &&
          item.all_goods &&
          item.share_discounts &&
          item.share_ms &&
          item.share_coupons &&
          item.new_member
        ) {
          notSelectedArr.push(item);
        }
      });

      const singleDisabled = notSelectedArr.length ? false : true;

      this.setData({
        singleDisabled,
      });
    } else {
      const {
        uniformDistributionList,
        uniformNewGoods,
        uniformHotGoods,
        uniformAllGoods,
        uniformShareDiscounts,
        uniformShareMs,
        uniformShareCoupons,
        uniformNewMember,
      } = this.data;
      const hasSelected = uniformDistributionList.find(item => item.checked === true);
      const uniformDisabled =
        hasSelected &&
        uniformNewGoods &&
        uniformHotGoods &&
        uniformAllGoods &&
        uniformShareDiscounts &&
        uniformShareMs &&
        uniformShareCoupons &&
        uniformNewMember;
      this.setData({
        uniformDisabled: !uniformDisabled,
      });
    }
  },

  onClearAll() {
    const { singleDistributionList } = this.data;
    singleDistributionList[0].list.map(item => {
      item.new_goods = '';
      item.hot_goods = '';
      item.all_goods = '';
      item.share_discounts = '';
      item.share_ms = '';
      item.share_coupons = '';
      item.new_member = '';
    });

    this.setData(
      {
        singleDistributionList,
      },
      () => {
        this.handleCalculateTotal();
        this.checkButtonStatus();
      },
    );
  },

  handleClearUniform() {
    const { uniformDistributionList } = this.data;

    uniformDistributionList.map(item => (item.checked = false));

    this.setData({
      uniformDistributionList,
      uniformNewGoods: '',
      uniformHotGoods: '',
      uniformAllGoods: '',
      uniformShareDiscounts: '',
      uniformShareMs: '',
      uniformShareCoupons: '',
      uniformNewMember: '',
      selectedNumber: 0,
      isSelectAll: false,
    });
  },

  togglesMask() {
    const { showMask } = this.data;

    if(!showMask) {
      this.handleClearUniform();
    }
    
    this.setData({
      showMask: !showMask,
    });
  },

  handleSelect(e) {
    const { uniformDistributionList } = this.data;
    const { id = '' } = e.currentTarget.dataset;
    uniformDistributionList.map(item => {
      if (String(item.id) === String(id)) {
        item.checked = !item.checked;
      }
    });

    this.setData(
      {
        uniformDistributionList,
      },
      () => {
        this.checkSelectStatus();
        this.checkButtonStatus('uniform');
      },
    );
  },

  handleSelectAll() {
    const { uniformDistributionList, isSelectAll } = this.data;
    uniformDistributionList.map(item => (item.checked = !isSelectAll));

    this.setData(
      {
        uniformDistributionList,
        isSelectAll: !isSelectAll,
      },
      () => {
        this.checkSelectStatus();
        this.checkButtonStatus('uniform');
      },
    );
  },

  checkSelectStatus() {
    const { uniformDistributionList } = this.data;
    const isSelectAll = !uniformDistributionList.find(item => item.checked === false);
    const selectedNumber = uniformDistributionList.filter(item => item.checked).length;

    this.setData({
      isSelectAll,
      selectedNumber,
    });
  },

  onTab(e) {
    const { currentIndex } = this.data;
    const { index = '', item } = e.currentTarget.dataset;

    if (Number(currentIndex) === Number(index)) {
      return;
    }

    this.setData(
      {
        currentIndex: item.value,
        week: item.value,
        toView: 'item' + item.value,
      },
      () => {
        this.getInfo();
      },
    );
  },
});
